<?php

namespace app\zyhsapi\model;

use think\Log;
use XznsTools\cache\zyhs\CacheManageZyhs;

/**
 * 合盘结果记录
 */
class ZyhsSynastryResult extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_synastry_result';

    protected $cacheModel = 'user.synastry';
    /**
     * 缓存id键名 为空时不更新
     * @var string
     */
    protected $cacheIdKey = 'id';

    /**
     * 开启了缓存
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('id', $ids);
            } else
            {
                $this->where('uid', $type[0]);
            }

            $synastryResult = $this->where('status', 1)
                ->order('id ' . $sortType)
                ->column('uid,create_time,update_time,nickname1,nickname2,avatar1,avatar2,score,relation,extra,type,rid1,rid2', 'id');

            foreach ($synastryResult as $id => $item)
            {
                $synastryResult[$id]['order_score'] = $item['update_time'] + ($id / 100000000);
            }
        }
        catch (\Exception $e)
        {
            Log::write('合盘结果获取异常：' . $e->getMessage(), 'error', true);
            return [];
        }

        return $synastryResult;
    }


    /**
     * 保存合盘记录
     * 若分数超过排行榜最低分，需要更新榜单
     * uid 合盘的用户id
     * type tinyint 1=>普通合盘 2=>明星合盘
     * rid1 ing rid1
     * rid2 int rid2
     * create_time bigint 创建时间
     * update_time bigint 更新时间
     * nickname1 varchar(50) 档案1昵称
     * nickname2 varchar(50) 档案2昵称
     * avatar1 string 档案1头像
     * avatar2 string 档案2头像
     * score int 合盘分数
     * relation string 最适合的关系
     * extra json 保存合盘的两个档案信息
     * @param array $data
     * @return bool|int
     */
    public function saveData(array $data = [])
    {
        try
        {
            $id = null;
            if (isset($data['rid1'], $data['rid2']) && $data['rid1'] && $data['rid2'])
            {
                $id = $this->where(['uid' => $data['uid'], 'status' => 1, 'type' => $data['type'], 'rid1' => $data['rid1'], 'rid2' => $data['rid2']])->value('id');
            }

            if ($id)
            {
                unset($data['create_time']);
                $this->allowField(true)->isUpdate(true)->save($data, ['id' => $id]);
            } else
            {
                $id = $this->allowField(true)->insertGetId($data);
            }

            $score = ($data['update_time'] ?? 0) + ($id / 100000000);
            // 写入缓存 列表缓存
            $this->listDataAdd($data['uid'], [$id => $score]);
        }
        catch (\Exception $e)
        {
            Log::write('合盘记录数据写入错误：' . $e->getMessage(), 'error', true);
            return false;
        }

        return $id;
    }

    /**
     * 删除/隐藏合盘记录
     * 更新 status=0,update_time=删除时间
     * @param int $uid 用户id
     * @param int $id 合盘记录id
     * @return bool
     */
    public function delData($uid, $id)
    {
        try
        {
            $this->where(['id' => $id])->update(['status' => 0, 'update_time' => time()]);

            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
            // 删除缓存 列表缓存
            $this->listDataDel($uid, [$id]);
        }
        catch (\Exception $e)
        {
            Log::write('合盘记录数据删除错误：' . $e->getMessage(), 'error', true);
            return false;
        }
        return true;
    }

    /**
     * 获取用户合盘记录
     * @param int $uid
     * @param int $page
     * @param int $limit
     * @return array|mixed
     * @throws \Exception
     */
    public function getUserList($uid = 0, $page = 1, $limit = 10)
    {
        $pageData = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setPageSize($limit)
            ->setSort('desc')
            ->setListKeyType(0)// 类型 用于分页 例如 0全部
            ->getListPage(function ($ids, $isCache = true, $sortType = 'asc') use ($uid, $page, $limit)
            {
                // 开启了缓存
                if ($isCache)
                {
                    return $this->getInfoByIdsInData($ids, [$uid, 0], $sortType);
                }

                // 没开启缓存
                return $this->getUserPaginateInData($uid, $sortType, $page, $limit);
            }, 'order_score', ['id', 'score', 'nickname1', 'nickname2', 'avatar1', 'avatar2', 'relation', 'create_time', 'type'], 0);

        $data = [];
        foreach ($pageData['data'] as $datum)
        {
            $data[] = [
                'id' => (int)$datum['id'],
                'score' => (int)$datum['score'],
                'nickname1' => $datum['nickname1'],
                'nickname2' => $datum['nickname2'],
                'avatar1' => $datum['avatar1'],
                'avatar2' => $datum['avatar2'],
                'relation' => $datum['relation'],
                'create_time' => (int)$datum['create_time'],
                'type' => in_array((int)$datum['type'], [5, 6], true) ? (int)$datum['type'] : 1,
            ];
        }
        $pageData['data'] = $data;

        return $pageData;
    }

    /**
     * 没开启缓存
     * @param $uid
     * @param string $sortType
     * @param $page
     * @param $limit
     * @return array|false|string
     */
    public function getUserPaginateInData($uid, $sortType, $page, $limit)
    {
        try
        {
            $synastryResult = $this
                ->where('uid', $uid)
                ->where('status', 1)
                ->order("update_time {$sortType},id {$sortType}")
                ->field('id,create_time,nickname1,nickname2,avatar1,avatar2,score,relation,extra')
                ->paginate($limit, false, ['page' => $page]);
        }
        catch (\Exception $e)
        {
            Log::write('合盘结果获取异常：' . $e->getMessage(), 'error', true);
            return [];
        }

        return $synastryResult;
    }

    /**
     * 档案删除 -- 将该档案合盘记录类型改为3【合盘类型 1=>普通合盘 2=>明星合盘 3=>有档案被删除  4=>活动邀请合盘未创建档案】
     * @param int $rid
     * @param int $uid
     */
    public function recodeDel(int $rid, int $uid): void
    {
        try
        {
            // 获取当前档案的合盘数据IDS
            $ids = $this->where(['uid' => $uid, 'status' => 1, 'rid1|rid2' => $rid])->column('id');
            // 更新数据库内数据状态
            $this->whereIn('id', $ids)->update(['type' => 3]);
            foreach ($ids as $id)
            {   // 更新缓存
                CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache(['type' => 3]);
            }
        }
        catch (\Exception $e)
        {
            Log::write('档案删除，更新档案合盘记录类型错误：' . $e->getMessage(), 'error', true);
        }
    }
}
